<?php namespace Phpcmf\Controllers\Admin;

class Finecms extends \Phpcmf\Common
{

    public $db;
    public $fdb;

    public function index() {
        
		\Phpcmf\Service::V()->admin();
		
		$page = (int)\Phpcmf\Service::L('Input')->get('page');
		if (!$page) {
			$this->_admin_msg(1, '正在准备升级', dr_url('finecms/index', ['page' => 1]));
		}

        if (!is_file(WRITEPATH.'config/database.php')) {
            exit('没有找到FineCMS的数据库配置文件：cache/config/database.php');
        }


		$this->db = \Phpcmf\Service::M()->db;
		$this->fdb = \Config\Database::connect('finecms');

		// 升级站点
		$site = $this->fdb->table('site')->where('id', 1)->get()->getRowArray();
		$this->db->table('site')->where('id', 1)->update([
		    'name' => $site['name'],
		    'domain' => $site['domain'],
        ]);

		// 升级模块
        $module = $this->fdb->table('module')->where('disabled=0')->get()->getResultArray();
        if ($module) {
            foreach ($module as $mod) {
                $dir = $mod['dirname'];
                $site = dr_string2array($mod['site']);
                // 卸载已经存在的模块
                \Phpcmf\Service::M('Module')->uninstall($dir);
                // 创建模块
                // 开始复制到指定目录
                $path = APPSPATH.ucfirst($dir).'/';
                \Phpcmf\Service::L('File')->copy_file(FCPATH.'Temp/Module/', $path);
                if (!is_file($path.'Config/App.php')) {
                    exit('文件创建失败：'.$path.'Config/App.php');
                }
                // 替换模块配置文件
                $app = file_get_contents($path.'Config/App.php');
                $app = str_replace(['{name}', '{icon}'], [$site['name'], 'fa fa-code'], $app);
                file_put_contents($path.'Config/App.php', $app);
                // 安装模块
                $cfg = require $path.'Config/App.php';
                $cfg['share'] = 1;
                $rt = \Phpcmf\Service::M('Module')->install($dir, $cfg);
                if (!$rt['code']) {
                    exit('模块['.$dir.']安装失败：'.$rt['msg']);
                }
                $new_id = $rt['data']['id'];
                // 同步自定义字段
                $fields = $this->fdb->table('field')->where('relatedname', 'module')->where('relatedid', $mod['id'])->get()->getResultArray();
                if ($fields) {
                    \Phpcmf\Service::M('Field')->func = 'module';
                    \Phpcmf\Service::M('Field')->data = $rt['data'];
                    \Phpcmf\Service::M('Field')->relatedid = $new_id;
                    \Phpcmf\Service::M('Field')->relatedname = 'module';
                    foreach ($fields as $field) {
                        if (!in_array($field['fieldname'], ['title','thumb','keywords','description','content'])) {
                            $field['setting'] = dr_string2array($field['setting']);
                            $field['relatedid'] = $new_id;
                            $sql = \Phpcmf\Service::L('field')->get($field['fieldtype'])->create_sql($field['fieldname'], $field['setting']['option'], $field['name']);
                            $rt = \Phpcmf\Service::M('Field')->add($field,  $sql );
                            if (!$rt['code']) {
                                exit('模块['.$dir.']字段['.$field['fieldname'].']创建失败：'.$rt['msg']);
                            }
                        }
                    }
                    // 同步数据
                    if (1) {
                        // 主表
                        $main = $this->fdb->table('1_'.$dir)->get()->getResultArray();
                        if ($main) {
                            foreach ($main as $t) {
                                $t['link_id'] = 0;
                                $t['avgsort'] = 0;
                                $t['support'] = 0;
                                $t['oppose'] = 0;
                                $t['donation'] = 0;
                                $t['tableid'] = 0;
                                $rt = \Phpcmf\Service::M()->table('1_'.$dir)->replace($t);
                                if (!$rt['code']) {
                                    exit('模块['.$dir.']同步数据失败：'.$rt['msg']);
                                }
                            }
                        }
                        $data = $this->fdb->table('1_'.$dir.'_data_0')->get()->getResultArray();
                        if ($data) {
                            foreach ($data as $t) {
                                $rt = \Phpcmf\Service::M()->table('1_'.$dir.'_data_0')->replace($t);
                                if (!$rt['code']) {
                                    exit('模块['.$dir.']同步数据失败：'.$rt['msg']);
                                }
                            }
                        }
                    }
                }

            }
        }

        // 共享主表
        $index = $this->fdb->table('1_index')->get()->getResultArray();
        if ($index) {
            $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('1_share_index').'`');
            foreach ($index as $t) {
                $rt = \Phpcmf\Service::M()->table('1_share_index')->replace([
                    'id' => $t['id'],
                    'mid' => $t['mid'],
                ]);
                if (!$rt['code']) {
                    exit('index同步数据失败：'.$rt['msg']);
                }
            }
        }

        // 同步栏目
        $category = $this->fdb->table('1_category')->get()->getResultArray();
        if ($category) {
            $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('1_share_category').'`');
            // 同步自定义字段
            $fields = $this->fdb->table('field')->where('relatedname', 'category-share')->where('relatedid', 0)->get()->getResultArray();
            if ($fields) {
                \Phpcmf\Service::M('Field')->func = 'category';
                \Phpcmf\Service::M('Field')->data = '-hare';
                \Phpcmf\Service::M('Field')->relatedid = 0;
                \Phpcmf\Service::M('Field')->relatedname = 'category-share';
                foreach ($fields as $field) {
                    $field['setting'] = dr_string2array($field['setting']);
                    $field['relatedid'] = 0;
                    $sql = \Phpcmf\Service::L('field')->get($field['fieldtype'])->create_sql($field['fieldname'], $field['setting']['option'], $field['name']);
                    $rt = \Phpcmf\Service::M('Field')->add($field,  $sql );
                    if (!$rt['code']) {
                        exit('栏目字段['.$field['fieldname'].']创建失败：'.$rt['msg']);
                    }
                }
            }
            foreach ($category as $t) {
                unset($t['letter']);
                unset($t['pcatpost']);
                unset($t['permission']);
                $rt = \Phpcmf\Service::M()->table('1_share_category')->replace($t);
                if (!$rt['code']) {
                    exit('栏目同步数据失败：'.$rt['msg']);
                }
            }
        }

        // 网站表单
        $form = $this->fdb->table('1_form')->get()->getResultArray();
        if ($form) {
            $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('1_form').'`');
            foreach ($form as $fm) {
                $rt = \Phpcmf\Service::M('Form')->create([
                    'name' => $fm['name'],
                    'table' => $fm['table'],
                ]);
                if (!$rt['code']) {
                    exit('表单['.$fm['name'].']创建失败：'.$rt['msg']);
                }
                // 同步自定义字段
                $fields = $this->fdb->table('field')->where('relatedname', 'form-1')->where('relatedid', $fm['id'])->get()->getResultArray();
                $this->db->table('field')->where('relatedname', 'form-1')->where('relatedid', $rt['code'])->delete();
                if ($fields) {
                    \Phpcmf\Service::M('Field')->relatedid = $rt['code'];
                    \Phpcmf\Service::M('Field')->relatedname = 'form-1';
                    \Phpcmf\Service::M('Field')->func = 'form';
                    \Phpcmf\Service::M('Field')->data = \Phpcmf\Service::M()->table('1_form')->get($rt['code']);;
                    foreach ($fields as $field) {
                        if (!in_array($field['fieldname'], ['title'])) {
                            $field['setting'] = dr_string2array($field['setting']);
                            $field['relatedid'] = \Phpcmf\Service::M('Field')->relatedid;
                            $sql = \Phpcmf\Service::L('field')->get($field['fieldtype'])->create_sql($field['fieldname'], $field['setting']['option'], $field['name']);
                            $rt = \Phpcmf\Service::M('Field')->add($field, $sql);
                            if (!$rt['code']) {
                                exit('表单字段[' . $field['fieldname'] . ']创建失败：' . $rt['msg']);
                            }
                        }
                    }
                }
                // 主表
                $dir = $fm['table'];
                $main = $this->fdb->table('1_form_'.$dir)->get()->getResultArray();
                if ($main) {
                    foreach ($main as $t) {
                        $t['status'] = 1;
                        $t['tableid'] = 0;
                        $rt = \Phpcmf\Service::M()->table('1_form_'.$dir)->replace($t);
                        if (!$rt['code']) {
                            exit('表单['.$dir.']同步数据失败：'.$rt['msg']);
                        }
                    }
                }
                $data = $this->fdb->table('1_form_'.$dir.'_data_0')->get()->getResultArray();
                if ($data) {
                    foreach ($data as $t) {
                        $rt = \Phpcmf\Service::M()->table('1_form_'.$dir.'_data_0')->replace($t);
                        if (!$rt['code']) {
                            exit('表单['.$dir.']同步数据失败：'.$rt['msg']);
                        }
                    }
                }

            }
        }

		// 自定义内容
        $data = $this->fdb->table('1_block')->get()->getResultArray();
		if ($data) {
            $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('1_block').'`');
		    foreach ($data as $t) {
		        $t['code'] = $t['id'];
                $rt = \Phpcmf\Service::M()->table('1_block')->replace($t);
                if (!$rt['code']) {
                    exit('自定义内容同步数据失败：'.$rt['msg']);
                }
            }
        }

		// tag
        $data = $this->fdb->table('1_tag')->get()->getResultArray();
		if ($data) {
            $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('1_tag').'`');
		    foreach ($data as $t) {
                $rt = \Phpcmf\Service::M()->table('1_tag')->replace($t);
                if (!$rt['code']) {
                    exit('tag内容同步数据失败：'.$rt['msg']);
                }
            }
        }

		// 联动菜单
        $data = $this->fdb->table('linkage')->get()->getResultArray();
		if ($data) {
            $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('linkage').'`');
		    foreach ($data as $t) {
                $rt = \Phpcmf\Service::M('Linkage')->create([
                    'name' => $t['name'],
                    'code' => $t['code'],
                ]);
                if (!$rt['code']) {
                    exit('联动菜单创建失败：'.$rt['msg']);
                }
                // 同步内容
                $id = $rt['code'];
                $link = $this->fdb->table('linkage_data_'.$t['id'])->get()->getResultArray();
                if ($link) {
                    $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('linkage_data_'.$id).'`');
                    foreach ($link as $t) {
                        $rt = \Phpcmf\Service::M()->table('linkage_data_'.$id)->replace($t);
                        if (!$rt['code']) {
                            exit('联动菜单内容同步数据失败：'.$rt['msg']);
                        }
                    }
                }
            }
        }

        // urlrule
        $data = $this->fdb->table('urlrule')->get()->getResultArray();
        if ($data) {
            $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('urlrule').'`');
            foreach ($data as $t) {
                $rt = \Phpcmf\Service::M()->table('urlrule')->replace($t);
                if (!$rt['code']) {
                    exit('urlrule内容同步数据失败：'.$rt['msg']);
                }
            }
        }

        // 附件
        $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('attachment').'`');
        $this->db->query('TRUNCATE `'.\Phpcmf\Service::M()->dbprefix('attachment_data').'`');
        $data = $this->fdb->table('attachment')->get()->getResultArray();
        if ($data) {
            foreach ($data as $t) {
                $rt = \Phpcmf\Service::M()->table('attachment')->replace($t);
                if (!$rt['code']) {
                    exit('attachment内容同步数据失败：'.$rt['msg']);
                }
            }
        }
        for ($i=0; $i<9; $i++) {
            $data = $this->fdb->table('attachment_'.$i)->get()->getResultArray();
            if ($data) {
                foreach ($data as $t) {
                    $rt = \Phpcmf\Service::M()->table('attachment_data')->replace($t);
                    if (!$rt['code']) {
                        exit('attachment内容同步数据失败：'.$rt['msg']);
                    }
                }
            }
        }



        echo "<h3>数据同步成功</h3>";
        echo "<p>请在PHP7CMS后台重新配置相关属性</p>";

        echo "<br><br>";

        echo "<h3>模板转移方法(default为例)：</h3>";
        echo "<p>将FineCMS模板目录templates\pc\default\common放到PHP7CMS目录template/pc/default/home</p>";
        echo "<p>将FineCMS风格目录statics/default放到PHP7CMS目录static/default</p>";

        echo "<br><br>";

        echo "<h3>附件转移方法：</h3>";
        echo "<p>将FineCMS的uploadfile复制到PHP7CMS之中</p>";

        echo "<br><br>";

        echo "<h3 style='color: red'>请删除文件：cache/config/database.php</h3>";

        exit;
		
    }

    

}
